const { Controller } = require("egg");
const { wxData } = require("../../config/data");
const crypto = require('crypto');

/** 重新获取限制 */
let reGetTime = false;
let jsapi_ticket_res = {};
/** 拿取wx公众号appid和密钥 */
const appid = wxData.appid;
const secret = wxData.secret;
/** 随机字符串 */
let noncestr;
/** 时间戳 */
let timestamp;
/** sha1签名 */
let sha1;

class UseJssdk extends Controller {

    async accessTokenInterface() {
        const ctx = this.ctx;
        ctx.set('Access-Control-Allow-Origin', '*');
        /** 设置重新获取限制 */
        if (reGetTime) return await this.responceRequest(true);
        /** 请求微信公众平台 */
        const res = await this.requsetService();
        /** 验证是否出错 */
        if (res && res.isErr) return this.throwErr(res.data.code, res.data.msg);
        /** 计算签名 */
        await this.computAccess();
        /** 响应请求数据 */
        await this.responceRequest();
        /** 打开请求限制并且,开始限制倒计时 */
        reGetTime = true;
        setTimeout(() => reGetTime = false, 7200 * 1000);
    }
    /** 请求 */
    async requsetService() {
        const ctx = this.ctx;
        /** 获取 access_token */
        const access_token_url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`;
        const access_token_res = await ctx.curl(access_token_url, { dataType: 'json', timeout: 3000 });

        if (access_token_res.status != 200) return { isErr: true, data: { code: 1001, msg: "请求 access_token 时出错" } };

        if (access_token_res.data.access_token == undefined) return { isErr: true, data: { code: access_token_res.data.errcode, msg: `获取 access_token 失败: ${access_token_res.data.errmsg}` } }
        /** 获取 jsapi_ticket */
        const jsapi_ticket_url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token_res.data.access_token}&type=jsapi`;
        jsapi_ticket_res = await ctx.curl(jsapi_ticket_url, { dataType: 'json', timeout: 3000 });

        if (access_token_res.status != 200) return { isErr: true, data: { code: 1002, msg: "请求 jsapi_ticket 时出错" } };
    }
    /** 计算签名 */
    async computAccess() {
        noncestr = `kujomiva${Math.random()}`;
        timestamp = new Date().getTime();
        /** 拼接字符串 */
        const str = `jsapi_ticket=${jsapi_ticket_res.data.ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${wxData.url}`;
        /** sha1加密 */
        sha1 = crypto.createHash('sha1').update(str).digest("hex").toUpperCase();
    }
    /** 抛错 */
    async throwErr(errNum = 404, errMsg = "not fond") {
        const time = new Date().getTime();
        this.ctx.body = {
            code: errNum,
            msg: errMsg,
            time: time
        }
    }
    /** 响应请求数据 */
    async responceRequest(isBuffer = false) {
        const time = new Date().getTime();
        /** 发送数据 */
        this.ctx.body = { noncestr, timestamp, sha1, time };
        /** 如果是缓存数据 */
        if (isBuffer) this.ctx.body.tip = "获取缓存数据";
    }

};

module.exports = UseJssdk;